package com.connector.base.codec;

import com.alibaba.fastjson.JSONObject;
import com.connector.base.protocol.Packet;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public final class PacketDecoder extends ByteToMessageDecoder
{
    private static final Logger log;

    protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
        if (in.readableBytes() >= 10) {
            in.markReaderIndex();
            final Packet packet = this.decodeFrame(in);
            if (packet != null) {
                out.add(packet);
            }
            else {
                in.resetReaderIndex();
            }
        }
    }

    public Packet decodeFrame(final ByteBuf in) {
        final int readableBytes = in.readableBytes();
        final int bodyLength = in.readInt();
        if (readableBytes < bodyLength + 10) {
            return null;
        }
        final Packet packet = new Packet();
        Packet.decodePacket(packet, in, bodyLength);
        return packet;
    }

    public static Packet decodeFrame(final String frame) {
        if (frame == null) {
            return null;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(frame);
            final Packet packet = new Packet(jsonObject.getByte("cmd"), jsonObject.getByte("type"));
            final Integer sessionId = jsonObject.containsKey((Object)"sessionId") ? jsonObject.getInteger("sessionId") : null;
            if (sessionId != null) {
                packet.setSessionId(sessionId);
            }
            final String body = jsonObject.containsKey((Object)"body") ? jsonObject.getString("body") : null;
            if (!Strings.isNullOrEmpty(body)) {
                final byte[] bytes = body.getBytes(Charsets.UTF_8);
                packet.setBody(bytes);
                packet.setBodyLength(bytes.length);
            }
            return packet;
        }
        catch (Exception e) {
            PacketDecoder.log.error("解析返回packet对象出现异常:[" + frame + "],不再执行往下执行", (Throwable)e);
            return null;
        }
    }

    static {
        log = LoggerFactory.getLogger((Class) PacketDecoder.class);
    }
}
